package org.hhy.cloud.crawl.controller;

import cn.hutool.core.collection.CollectionUtil;
import org.assertj.core.util.Lists;
import org.hhy.cloud.crawl.entity.JobMonitor;
import org.hhy.cloud.crawl.service.JobMonitorService;
import org.hhy.cloud.crawl.vo.JobMonitorVO;
import org.lht.boot.cache.redis.RedisUtil;
import org.lht.boot.lang.util.R;
import org.lht.boot.web.api.param.PagerResult;
import org.lht.boot.web.api.param.QueryParam;
import org.lht.boot.web.api.param.util.ParamServletUtil;
import org.lht.boot.web.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.Set;

import static org.hhy.cloud.crawl.constant.CrawlConstant.RedisKey.JOB_MONITOR_STATUS_KEY;

/**
 * Description: 爬虫监控controller
 *
 * @Author lht
 * @Date 2020/11/7 3:46 PM
 **/
@RestController
@RequestMapping("/job_monitor")
public class JobMonitorController extends AbstractController<JobMonitor, String, JobMonitorVO, JobMonitorService> {

    @Autowired
    private RedisUtil<String, JobMonitor> redisUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private JobMonitorService jobMonitorService;

    @Override
    public R<PagerResult<JobMonitorVO>> selectPage(QueryParam param, HttpServletRequest request) {

        Set<String> keys = stringRedisTemplate.keys(JOB_MONITOR_STATUS_KEY + "*");
        if (CollectionUtil.isNotEmpty(keys)) {
            List<JobMonitor> cacheResult= Lists.newArrayList();
            keys.forEach(k -> {
                JobMonitor jobMonitor = redisUtil.get(k);
                cacheResult.add(jobMonitor);
            });
            jobMonitorService.upsert(cacheResult);
        }

        ParamServletUtil.paddingTerms(param, request);
        PagerResult<JobMonitor> pagerResult = getService().selectPager(param);
        if (CollectionUtil.isEmpty(pagerResult.getRecords())) {
            return R.ok(new PagerResult<JobMonitorVO>());
        }

        return R.ok(pagerResult.convertTo(this::entityToVo));
    }
}
